<template>
  <div class="loginPage">
    <el-form
      :hide-required-asterisk="true"
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      class="demo-ruleForm"
    >
      <h2>叩丁狼管理平台</h2>
      <el-form-item prop="username">
        <el-input
          type="text"
          v-model="ruleForm.username"
          autocomplete="off"
          placeholder="账号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          autocomplete="off"
          placeholder="密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          style="width: 100%"
          type="primary"
          @click="submitForm('ruleForm')"
        >
          登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { loginApi, getUserInfo } from "../../request/api";
export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { validator: this.checkForm, trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    getUserInfo().then((res) => {
      if (res.errno === 0) {
        console.log(res);
      }
    });
  },
  methods: {
    // 登录按钮
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        console.log(valid);
        if (valid) {
          loginApi({
            password: this.ruleForm.password,
            username: this.ruleForm.username,
          }).then((res) => {
            if (res.errno === 0) {
              localStorage.setItem("token", res.data.token);
              this.$router.push("/homepage");
            }
          });
        }
      });
    },
    // 规则校验
    checkForm(rule, value, callback) {
      if (value && value.length >= 3) {
        callback();
      } else {
        callback("长度不小于3");
      }
    },
  },
};
</script>
 
<style lang = "less" scoped>
.loginPage {
  height: 100%;
  position: relative;
  background-color: #2d3a4b;
  .el-form {
    width: 420px;
    height: 250px;
    position: absolute;
    top: 50%;
    margin-top: -125px;
    margin-left: -210px;
    left: 50%;
    h2 {
      text-align: center;
      margin-bottom: 10px;
      color: #fff;
    }
  }
}
</style>